package face.pay.api.alipay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AppTokenExchangeSubElement;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.face.pay.AliPayConfig;
import com.face.pay.IPayConfigServer;
import face.pay.api.alipay.service.IAliPayAuthService;
import face.pay.dao.EnterpriseInfoDao;
import face.pay.dao.UserInfoDao;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.UserInfo;
import face.pay.redis.RedisUtils;
import face.pay.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alipay.api.AlipayConstants.APP_ID;

/**
 * 支付宝应用授权
 */
@Service
@Slf4j
public class AliPayAuthServiceImpl implements IAliPayAuthService {

    @Autowired
    public IPayConfigServer iWxPayConfigServer;

    @Autowired
    EnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public ResultMessage auth(String app_auth_code, String app_id, String state) {

        String key="ALI_AUTH_"+state;

        try{
            if(StringUtils.isNotBlank(app_auth_code)){
                Object cache_validateCode = redisUtils.get(key);

                log.error("盘算是否已经存在授权");
                if(cache_validateCode!=null){
                    log.error("已经授权");
                    return ResultMessage.createFail("授权处理成功，商户确认");
                }
                redisUtils.set(key,state,600);

                Integer userId = Integer.valueOf(state);

                UserInfo userInfo = this.userInfoDao.getById(userId);
                if(userInfo==null){
                    return  ResultMessage.createFail("授权失败用户不存在");
                }
                if (userInfo.getDeleted() == 1) {
                    return ResultMessage.createFail("授权失败用户已被注销");
                }

                AliPayConfig aliPayConfig = this.iWxPayConfigServer.getAliConfig(userInfo.getOemId());

                if(aliPayConfig.validate()){

                    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliPayConfig.getAppid(),aliPayConfig.getAppKey(),
                            "json", "utf-8", aliPayConfig.getAliPublicKey(),"RSA2");

                    AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();

                    Map<String,String>  map =  new HashMap<String,String>();

                    map.put("grant_type","authorization_code");
                    map.put("code",app_auth_code);
                    request.setBizContent(JSON.toJSONString(map));
                    AlipayOpenAuthTokenAppResponse response =alipayClient.execute(request);
                    log.error("授权返回");
                    log.error(JSON.toJSONString(response));
                    String code = response.getCode();
                    String message = response.getMsg();

                    if("10000".equals(code)){
                        log.error("返回成功 ");
                        if(response.isSuccess()){

                            log.error("获取token ");
                            List<AppTokenExchangeSubElement> tokens   = response.getTokens();

                            AppTokenExchangeSubElement token =tokens.get(0);

                            String app_auth_token = token.getAppAuthToken();

                            String aliUserId = token.getUserId();


                            EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(userId);

                            if(enterpriseInfo!=null){

                                if(StringUtils.isBlank(enterpriseInfo.getAliUserId())){
                                    enterpriseInfo.setAliUserId(aliUserId);
                                    enterpriseInfo.setAliToken(app_auth_token);
                                    log.error("未绑定支付宝商家 立即绑定 ");
                                    this.enterpriseInfoDao.update(enterpriseInfo);
                                    return ResultMessage.createSuccess("授权成功");
                                }else {

                                    String pid = enterpriseInfo.getAliUserId();
                                    if(aliUserId.equals(pid)){
                                        enterpriseInfo.setAliToken(app_auth_token);
                                        this.enterpriseInfoDao.update(enterpriseInfo);
                                        log.error("已经绑定 刷新授权");
                                        return ResultMessage.createSuccess("已授权");
                                    }else {
                                        log.error("已经绑定 刷新授权失败 两次PID 不");
                                        return ResultMessage.createSuccess("授权失败，本次授权与第一次授权时支付宝信息不匹配");

                                    }


                                }


                            }
                        }

                    }else {
                        return ResultMessage.createFail("授权失败");
                    }

                }else {
                    log.error("服务商配置错误");
                    return ResultMessage.createFail("服务商配置错误 授权失败");
                }
            }else {
                log.error("授权处理成功，商户确认");
                return ResultMessage.createFail("授权处理成功，商户确认");
            }

        }catch (Exception e){
            log.error("商家授权异常",e);
        }
        return ResultMessage.createFail("授权失败");
    }
}
